// pages/PJ2/PJ2.js
const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    num: 4,//后端给的分数,显示相应的星星
    one_1: 0,
    two_1: 5,
    one_2: 0,
    two_2: 5,
    one_3: 0,
    two_3: 5,
    title:'',
    imgbox: [],
    fileIDs:[],

    Orders:[]
  },
  return:function(){
    wx.navigateBack({
      delta: 1
    })
  },
  //情况二:用户给评分
  in_xin:function(e){
    var in_xin = e.currentTarget.dataset.in;
    var id=e.currentTarget.dataset.id;
    var Num;
    if(id==1){
      if (in_xin === 'use_sc2'){
        Num = Number(e.currentTarget.id);
      } else {
        Num = Number(e.currentTarget.id) + this.data.one_1;
      }
      this.setData({
        one_1: Num,
        two_1: 5 - Num
      })
    }else if(id==2){
      if (in_xin === 'use_sc2'){
        Num = Number(e.currentTarget.id);
      } else {
        Num = Number(e.currentTarget.id) + this.data.one_2;
      }
      this.setData({
        one_2: Num,
        two_2: 5 - Num
      })
    }else{
      if (in_xin === 'use_sc2'){
        Num = Number(e.currentTarget.id);
      } else {
        Num = Number(e.currentTarget.id) + this.data.one_3;
      }
      this.setData({
        one_3: Num,
        two_3: 5 - Num
      })
    }
  },
  title:function(e){
    console.log(e.detail.value)
    this.setData({
      title:e.detail.value
    })
  },
  // 删除照片 &&
  imgDelete1: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.deindex;
    let imgbox = this.data.imgbox;
    imgbox.splice(index, 1)
    that.setData({
      imgbox: imgbox
    });
  },
  // 选择图片 &&&
  addPic1: function (e) {
    var imgbox = this.data.imgbox;
    console.log(imgbox)
    var that = this;
    var n = 5;
    if (5 > imgbox.length > 0) {
      n = 5 - imgbox.length;
    } else if (imgbox.length == 5) {
      n = 1;
    }
    wx.chooseImage({
      count: n, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // console.log(res.tempFilePaths)
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths

        if (imgbox.length == 0) {
          imgbox = tempFilePaths
        } else if (5 > imgbox.length) {
          imgbox = imgbox.concat(tempFilePaths);
        }
        that.setData({
          imgbox: imgbox
        });
      }
    })
  },
  submit:function(){
    var that=this
    var one_1=that.data.one_1
    var one_2=that.data.one_2
    var one_3=that.data.one_3
    var state=''
    var sum=one_1+one_2+one_3
    if(sum>=10){
      state="好"
    }else if(sum>=5){
      state="中"
    }else{
      state="差"
    }
    wx.showLoading({
      title: '评价中',
    })
    let promiseArr = [];
    for (let i = 0; i < that.data.imgbox.length; i++) {
      promiseArr.push(new Promise((reslove, reject) => {
        let item = this.data.imgbox[i];
        let suffix = /\.\w+$/.exec(item)[0];//正则表达式返回文件的扩展名
        wx.cloud.uploadFile({
          cloudPath: new Date().getTime() + suffix, // 上传至云端的路径
          filePath: item, // 小程序临时文件路径
          success: res => {
            this.setData({
              fileIDs: that.data.fileIDs.concat(res.fileID)
            });
            console.log(res.fileID)
            reslove();
          },
          fail: console.error
        })
      }));
    }
    Promise.all(promiseArr).then(res => {//等数组都做完后做then方法
      wx.getUserInfo({
        success: res => {
          // 可以将 res 发送给后台解码出 unionId
          console.log(res.userInfo.nickName)
          console.log(res.userInfo.avatarUrl)
          var avatarUrl=res.userInfo.avatarUrl
          var nickName=res.userInfo.nickName
          
          db.collection('Evaluate').add({
            data: {
              avatarUrl:avatarUrl,
              nickName:nickName,
              title: that.data.title,
              GoodsImg: that.data.Orders[0].GoodsImg,
              GoodsRmb:that.data.Orders[0].rmb,
              GoodsTitle:that.data.Orders[0].GoodsTitle,
              GoodsId:that.data.Orders[0].GoodsId,
              OrderRmb: (that.data.Orders[0].express+that.data.Orders[0].rmb/10.0*that.data.Orders[0].sale).toFixed(2),
              OrderSize: that.data.Orders[0].size,
              OrderColor: that.data.Orders[0].color,
              OrderNumber: that.data.Orders[0].number,
              img: that.data.fileIDs,
              one_1: that.data.one_1,
              one_2: that.data.one_2,
              one_3: that.data.one_3,
              OrderId:that.data.Orders[0].id,
              SellOpenid:that.data.Orders[0].SellOpenid,
              state:state,
              EvaluationTime:that.getNowDatTime()
            }
          }).then(res => {
            db.collection('Order').doc(that.data.Orders[0].id).update({
              data: {
                state:"交易完成"
              },
              success: function(res) {
                console.log(res.data)
                wx.hideLoading();
                wx.showToast({
                  title: "评价成功",
                })
              }
            })
          }).catch(err => {
            wx.hideLoading();
            wx.showToast({
              title: "评价失败",
            })
          })
          // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
          // 所以此处加入 callback 以防止这种情况
          if (this.userInfoReadyCallback) {
            this.userInfoReadyCallback(res)
          }
        }
      })
    })
  },
  //获取当前时间
  getNowDatTime:function(){
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
      month = "0" + month;
    }
    if (strDate >= 0 && strDate<=9) {
      strDate = "0" + strDate;
    }
    var time = date.getFullYear() + seperator1 + month + seperator1 + strDate
    console.log(time);
    return time;
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that=this
    console.log(options.id)
    that.getOrder(options.id);
  },
  getOrder:function(OrderId){
    var that=this
    wx.showLoading({
      title: '加载中',
    })
    db.collection('Order').doc(OrderId).get()
      .then(res => {
        // res.data 包含该记录的数据
        console.log(res.data)
        var id = "Orders[0].id"
          var Consignee = "Orders[0].Consignee"
          var DeliveryTime = "Orders[0].DeliveryTime"
          var GoodsId = "Orders[0].GoodsId"
          var ReceivingTime = "Orders[0].ReceivingTime"
          var CreationTime = "Orders[0].CreationTime"
          var PaymentTime = "Orders[0].PaymentTime"
          var Remarks = "Orders[0].Remarks"
          var SellOpenid = "Orders[0].SellOpenid"
          var Telephone = "Orders[0].Telephone"
          var openid = "Orders[0].openid"
          var address = "Orders[0].address"
          var color = "Orders[0].color"
          var number = "Orders[0].number"
          var rmb = "Orders[0].rmb"
          var size = "Orders[0].size"
          var state = "Orders[0].state"
          var GoodsTitle = "Orders[0].GoodsTitle"
          var SellNickName = "Orders[0].SellNickName"
          var SellAvatarUrl = "Orders[0].SellAvatarUrl"
          var GoodsImg = "Orders[0].GoodsImg"
          var express = "Orders[0].express"
          var CourierNumber="Orders[0].CourierNumber"
          var sale="Orders[0].sale"
          
          that.setData({
            [id] :res.data._id,
            [Consignee]:res.data.Consignee,
            [DeliveryTime]:res.data.DeliveryTime,
            [GoodsId]:res.data.GoodsId,
            [ReceivingTime]:res.data.ReceivingTime,
            [CreationTime]:res.data.CreationTime,
            [PaymentTime]:res.data.PaymentTime,
            [Remarks]:res.data.Remarks,
            [SellOpenid]:res.data.SellOpenid,
            [Telephone]:res.data.Telephone,
            [openid]:res.data._openid,
            [address]:res.data.address,
            [color]:res.data.color,
            [number]:res.data.number,
            [rmb]:res.data.rmb,
            [size]:res.data.size,
            [state]:res.data.state,
            [GoodsTitle]:res.data.GoodsTitle,
            [SellNickName]:res.data.SellNickName,
            [SellAvatarUrl]:res.data.SellAvatarUrl,
            [GoodsImg]:res.data.GoodsImg,
            [express]:res.data.express,
            [CourierNumber]:res.data.CourierNumber,
            [sale]:res.data.sale,
          })
          wx.hideLoading();
      })
      .catch(err => {
        console.error(err)
        wx.hideLoading();
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})